package com.remainder.resource.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.remainder.common.core.exception.BusinessException;
import com.remainder.common.core.web.controller.BaseController;
import com.remainder.common.core.web.page.TableDataInfo;
import com.remainder.common.security.annotation.RequiresPermissions;
import com.remainder.common.security.utils.SecurityUtils;
import com.remainder.resource.api.domain.ExportLogDto;
import com.remainder.resource.service.IExportLogService;

/**
 * 导出记录Controller
 *
 * @author yhf
 * @date 2023-06-13
 */
@RestController
@RequestMapping("/exportLog")
public class ExportLogController extends BaseController {
    @Autowired
    private IExportLogService exportLogService;

    /**
     * 查询导出记录列表
     */
    @RequiresPermissions("resource:exportLog:list")
    @GetMapping("/list")
    public TableDataInfo list(ExportLogDto exportLog) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        exportLog.setOperatorId(userId);
        // 管理员可看所有下载
        boolean isAdmin = SecurityUtils.isAdmin(userId);
        if (isAdmin) {
            exportLog.setOperatorId(null);
        }
        List<ExportLogDto> list = exportLogService.selectExportLogList(exportLog);
        return getDataTable(list);
    }

    /**
     * 本地记录下载
     */
    @RequiresPermissions("resource:exportLog:downLoadLocal")
    @PostMapping("downLoadLocal")
    public void getInfo(HttpServletResponse response, ExportLogDto req) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        ExportLogDto exportLog = exportLogService.selectExportLogById(req.getId());
        String path = exportLog.getExportDetails();

        try (FileInputStream in = new FileInputStream(path)) {
            ServletOutputStream out = response.getOutputStream();
            byte[] buf = new byte[8192];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (Exception e) {
            throw new BusinessException("文件下载异常", e);
        }
    }

}
